"use strict";
let mysql = require('mysql');
let mysqlConnectionPool = mysql.createPool(config.mysql);
exports.mysqlPool = mysqlConnectionPool;
exports.escape = mysql.escape;
exports.getConn = function () {
    return new Promise(function (resolve,reject) {
        mysqlConnectionPool.getConnection(function (err, conn) {
            if (err)
                reject(err);
            conn.isOpenTransaction = 0;
            conn.releaseConn = releaseConn.bind(conn);
            conn.openTransaction = openTransaction.bind(conn);
            conn.commitTransaction = commitTransaction.bind(conn);
            conn.rollbackTransaction = rollbackTransaction.bind(conn);
            resolve(conn);
        });
    });
};

/**
 * 释放连接
 */
let releaseConn = function () {
    try {
        this.release();
    } catch (err) {
        console.log(err);
        this.release();
    }
};
/**
 * 开启事务
 */
let openTransaction = function () {
    let self = this;
    return new Promise(function (resolve,reject) {
        self.beginTransaction(function (err, data) {
            if (err)
                reject(err);
            self.isOpenTransaction = 1;
            resolve(data);
        });
    });
};
/**
 * 提交事务
 */
let commitTransaction = function () {
    let self = this;
    return new Promise(function (resolve,reject) {
        self.commit(function (err, data) {
            if (err) {
                self.rollbackTransaction();
                reject(err);
            } else {
                resolve(data);
            }
        });
    });
};
/**
 * 回滚事务
 */
let rollbackTransaction = function () {
    let self = this;
    return new Promise(function (resolve,reject) {
        if (self.isOpenTransaction) {
            self.rollback(function (err, data) {
                if (err)
                    reject(err);
                resolve(data);
            });
        } else {
            resolve('next');
        }
    });
};
